/**
 * This file is Copyright © 2008 Software Craftsmen Limited. All Rights Reserved.
 */
package com.softwarecraftsmen.orogeny.application;

import com.softwarecraftsmen.orogeny.BuildScript;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import static java.lang.String.format;
import static java.util.Locale.UK;

public class BuildScriptLoader
{
	private final File scriptFile;

	public BuildScriptLoader(final @NotNull File scriptFile)
	{
		this.scriptFile = scriptFile;
	}

	@NotNull
	public Class<? extends BuildScript> loadScript(final @NotNull ClassLoader compiledClassLoader)
	{
		final Class<? extends BuildScript> buildScriptClass;
		try
		{
			buildScriptClass = loadScriptClass(compiledClassLoader, getCompiledScriptClassName());
		}
		catch (ClassNotFoundException e)
		{
			throw new RuntimeException(format(UK, "Could not find class %1$s in script %2$s", getCompiledScriptClassName(), scriptFile));
		}
		return buildScriptClass;
	}

	private String getCompiledScriptClassName()
	{
		final String fileName = scriptFile.getName();
		final int i = fileName.lastIndexOf(".");
		if (i == -1)
		{
			return fileName;
		}
		return fileName.substring(0, i);
	}

	// TODO: Be a bit more intelligent - don't assume no package
	@SuppressWarnings({"unchecked"})
	private Class<? extends BuildScript> loadScriptClass(final ClassLoader compiledClassLoader, final String compiledScriptClassName) throws ClassNotFoundException
	{
		final Class<?> compiledScriptClass = compiledClassLoader.loadClass(compiledScriptClassName);
		if (!BuildScript.class.isAssignableFrom(compiledScriptClass))
		{
			throw new IllegalStateException(format(UK, "Specified script %1$s is not a sub type of BuildScript", compiledScriptClass));
		}
		return (Class<? extends BuildScript>) compiledScriptClass;
	}
}
